<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016-09-06
 * Time: 19:33
 */

namespace iBrand\Shop\Server\Http\Controllers\O2oUser;

use iBrand\Component\Product\Models\Goods;
use iBrand\Server\Http\Controllers\Controller;
use iBrand\Shop\Server\Service\DiscountService;
use Illuminate\Http\Request;

class DiscountController extends Controller
{

    private $discountService;

    public function __construct(
        DiscountService $discountService
    )
    {
        $this->discountService = $discountService;
    }

    public function getDiscountByGoods($id)
    {
        $item = Goods::find($id);
        if (!$item) {
            return $this->api('', false);
        }

        $discounts = $this->discountService->getDiscountsByGoods($item);
        if (!$discounts || count($discounts) == 0) {
            return $this->api('', false);
        }

        $result['discounts'] = collect_to_array($discounts->where('coupon_based', 0));
        $result['coupons'] = collect_to_array($discounts->where('coupon_based', 1));

        //return $discounts->where('coupon_based', 1)->toArray();
        return $this->api($result);
    }

    public function shoppingCartDiscount(Request $request)
    {
        $input = $request->except('file', '_token');
        if (empty($input['ids'])) {
            return $this->api([], false, 500, '必填参数缺失');
        }

        $discount = [];
        $coupon = [];
        foreach ($input['ids'] as $id) {
            $goods = Goods::find($id);
            if (!$goods) {

                continue;
            }

            $discounts = $this->discountService->getDiscountsByGoods($goods);
            if (!$discounts || count($discounts) == 0) {

                continue;
            }

            $coupon_based_0 = collect_to_array($discounts->where('coupon_based', 0));
            foreach ($coupon_based_0 as $d) {
                if (!array_key_exists($d['id'], $discount)) {
                    $discount[$d['id']] = $d;
                }
            }

            $coupon_based_1 = collect_to_array($discounts->where('coupon_based', 1));
            foreach ($coupon_based_1 as $c) {
                if (!array_key_exists($c['id'], $coupon)) {
                    $coupon[$c['id']] = $c;
                }
            }
        }

        $result = ['coupons' => array_values($coupon), 'discounts' => array_values($discount)];

        return $this->api($result);
    }


}
